import { defineStore } from "pinia";
import { RouteRecordRaw } from "vue-router";
import { ElMessage } from "element-plus";

import { setToken, removeToken, getToken } from "@/utils/localStorage";
import { constantRoutes, anyRoutes, asyncRoutes } from "@/router/routes";
import { login, logout } from "@/apis/auth";
import type { ILoginParmas, ILoginResData } from "@/apis/auth/type";

const useAuthStore = defineStore("authStore", {
  state: (): {
    tokenJson: string;
    menuRoutes: RouteRecordRaw[];
    loading: boolean;
  } => {
    return {
      // 用户信息
      tokenJson: "",
      menuRoutes: [...constantRoutes, ...anyRoutes, ...asyncRoutes],
      loading: false,
    };
  },
  actions: {
    saveToken(data: ILoginResData) {
      this.tokenJson = JSON.stringify(data);
      setToken(this.tokenJson);
    },
    async userLogin(loginParmas: ILoginParmas) {
      this.loading = true;
      try {
        const res = await login(loginParmas);
        if (res.code === 200) {
          this.saveToken(res.data);
          ElMessage.success("登录成功");
          return true;
        }
      } catch (error: any) {
        ElMessage.error(error.message);
      } finally {
        this.loading = false;
      }
    },

    async userLogout() {
      this.loading = true;
      try {
        const res = await logout();
        if (res.code === 200) {
          this.tokenJson = "";
          removeToken();
          ElMessage.success("登录成功");
          return true;
        }
      } catch (error: any) {
        ElMessage.error(error.message);
      } finally {
        this.loading = false;
      }
    },
  },
  getters: {
    tokenObj: state => {
      try {
        return JSON.parse(
          state.tokenJson || getToken() || "{}"
        ) as ILoginResData;
      } catch (error) {
        ElMessage.error("token解析失败");
        removeToken();
        throw error;
      }
    },
  },
});

export default useAuthStore;
